package org.zebra.web.annotation.version;

import cn.hutool.core.text.CharSequenceUtil;
import lombok.Data;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zhanghongbin
 */
class ApiVersionConverter {

    /**
     * 接口路径中的版本号前缀，如: api/v1.0.0/test
     */
    public static final Pattern VERSION_PREFIX_PATTERN = Pattern.compile("/v(\\d+).(\\d+).(\\d+)");

    private ApiVersionConverter() {}

    public static ApiVersionVO convert(ApiVersion apiVersion) {
        String api = apiVersion.value();
        ApiVersionVO apiVersionVO = new ApiVersionVO(apiVersion);
        if (CharSequenceUtil.isBlank(api)) {
            return null;
        }
        return buildApiVersionVO(apiVersionVO, api);
    }

    public static ApiVersionVO parse(String url) {
        Matcher m = VERSION_PREFIX_PATTERN.matcher(url);
        if (m.find()) {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder
                    .append(m.group(1))
                    .append(".")
                    .append(m.group(2))
                    .append(".")
                    .append(m.group(3));
            ApiVersionVO apiVersionVO = new ApiVersionVO();
            return buildApiVersionVO(apiVersionVO, stringBuilder.toString());
        }
        return null;
    }

    private static ApiVersionVO buildApiVersionVO(ApiVersionVO apiVersionVO, String api) {
        String[] cells = CharSequenceUtil.splitToArray(api, ".");
        if (cells.length != 3) return null;
        apiVersionVO.setHigh(Integer.parseInt(cells[0]));
        if (cells.length > 1) {
            apiVersionVO.setMid(Integer.parseInt(cells[1]));
        }
        if (cells.length > 2) {
            apiVersionVO.setLow(Integer.parseInt(cells[2]));
        }
        return apiVersionVO;
    }
}

@Data
class ApiVersionVO implements Comparable<ApiVersionVO> {

    private ApiVersion apiVersion = null;

    private int high = 1;

    private int mid = 0;

    private int low = 0;

    public ApiVersionVO(ApiVersion apiVersion) {
        this.apiVersion = apiVersion;
    }

    public ApiVersionVO() {}

    @Override
    public int compareTo(ApiVersionVO right) {
        if (this.getHigh() > right.getHigh()) {
            return 1;
        } else if (this.getHigh() < right.getHigh()) {
            return -1;
        }

        if (this.getMid() > right.getMid()) {
            return 1;
        } else if (this.getMid() < right.getMid()) {
            return -1;
        }

        if (this.getLow() > right.getLow()) {
            return 1;
        } else if (this.getLow() < right.getLow()) {
            return -1;
        }
        return 0;
    }
}
